package com.sc.ktapplication.common.base

import android.app.ProgressDialog
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.sc.ktapplication.MyApp
import com.sc.ktapplication.R
import com.sc.ktapplication.common.util.StatusBarUtil
import com.sc.ktapplication.common.util.ToastUtil
import com.sc.ktapplication.module.entity.AppUser

abstract class BaseActivity : AppCompatActivity() {

    protected var mUser:AppUser ?= null
    private var mProgressDialog : ProgressDialog? = null
    private var mTxtTitle: TextView? = null

    abstract fun getLayoutId() : Int

    abstract fun showErrorMsg()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setStatusColor(this, false, true, R.color.white)
        MyApp.instance.addActivity(this)
        setContentView(getLayoutId())
        findViews()
        showTitle()
        mUser = MyApp.instance.getUser()
        showErrorMsg()
    }

    fun showLoadingDialog(){
        showLoadingDialog(null, true)
    }

    fun showLoadingDialog(msg: String?, cancelable: Boolean){
        initProgressDialog()
        if(!mProgressDialog!!.isShowing && !isFinishing){
            mProgressDialog!!.setMessage(msg ?: "正在加载，请稍后...")
            mProgressDialog!!.setCancelable(cancelable)
            mProgressDialog!!.show()
        }
    }

    private fun initProgressDialog(){
        if(null == mProgressDialog){
            mProgressDialog = ProgressDialog(this)
        }
    }

    open fun dismissLoadingDialog() {
        if (null != mProgressDialog && mProgressDialog!!.isShowing) {
            mProgressDialog!!.dismiss()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        dismissLoadingDialog()
        MyApp.instance.removeActivity(this)
    }

    protected fun showErrorMsg(view : View,viewModel: BaseViewModel) {
        viewModel.errorMsg.observe(this, Observer { msg ->
            dismissLoadingDialog()
            ToastUtil.snackbarLong(view,msg)
        })
    }

    private fun showTitle() {
        if (mTxtTitle != null) mTxtTitle!!.text=title
    }

    open fun onBackClick(view: View) {
        super.onBackPressed()
    }

    open fun onRightBtnClick(view: View) {}

    protected open fun findViews() {
        mTxtTitle = findViewById(R.id.txtTitle)
    }


}